package com.zx._03_并发.chapter_02_synchronized;

import org.openjdk.jol.info.ClassLayout;

public class 锁的内存布局 {

    public static void main(String[] args) {
        Object obj = new Object();

        // 1.无锁的状态
        printLayout(obj);

        // 调用hashCode后，字段为markWord填充31位hashCode值
        obj.hashCode();
        printLayout(obj);

        // 2. 偏向锁
        synchronized (obj) {
            printLayout(obj);
        }

    }

    public static void printLayout(Object obj) {
        System.out.println(ClassLayout.parseInstance(obj).toPrintable());
    }

    public void add(String s1) {
        StringBuffer sb = new StringBuffer();
        sb.append(s1);
    }
}
/*
synchronized 各个阶段都与markWord有关
markWord有64位，8个byte
1. new 
	java.lang.Object object internals:
	 OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
	      0     4        (object header)                           05 00 00 00 (00000101 00000000 00000000 00000000) (5)
	      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
	      8     4        (object header)                           94 20 00 00 (10010100 00100000 00000000 00000000) (8340)
	     12     4        (loss due to the next object alignment)
	Instance size: 16 bytes
	Space losses: 0 bytes internal + 4 bytes external = 4 bytes total


	obj.hashCode()
	java.lang.Object object internals:
	OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
	      0     4        (object header)                           01 2a 8f 75 (00000001 00101010 10001111 01110101) (1972316673)
	      4     4        (object header)                           11 00 00 00 (00010001 00000000 00000000 00000000) (17)
	      8     4        (object header)                           94 20 00 00 (10010100 00100000 00000000 00000000) (8340)
	     12     4        (loss due to the next object alignment)
	Instance size: 16 bytes
	
2. 偏向锁
	java.lang.Object object internals:																	第二个1表示偏向锁的位置
	 OFFSET  SIZE   TYPE DESCRIPTION                               VALUE							   --> 10000110 <--
	      0     4        (object header)                           05 78 d4 86 (00000101 01111000 11010100 10000101) (-2032895995)
	      4     4        (object header)                           95 02 00 00 (10010101 00000010 00000000 00000000) (661)
	      8     4        (object header)                           94 20 00 00 (10010100 00100000 00000000 00000000) (8340)
	     12     4        (loss due to the next object alignment)
	Instance size: 16 bytes
	Space losses: 0 bytes internal + 4 bytes external = 4 bytes total


	
	
3. 轻量锁（无锁、自旋锁、自适应自旋锁）

4. 重量锁

*/